package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.contxt.BaseContext;
import com.hmall.common.feign.address.Address;
import com.hmall.common.feign.address.AddressFeignClient;
import com.hmall.common.feign.item.Item;
import com.hmall.common.feign.item.ItemFeignClient;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDTO;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
@Transactional
@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressFeignClient addressFeignClient;
    @Autowired
    private ItemFeignClient itemFeignClient;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;
    //下单
    @Override
    public Long PlaceAnOrder(OrderDTO orderDTO) {
        //根据itemId查询商品信息
        Item item = itemFeignClient.findById(orderDTO.getItemId());
        //基于商品价格、购买数量计算商品总价：totalFee
        BigDecimal multiply = BigDecimal.valueOf(item.getPrice()).multiply(BigDecimal.valueOf(orderDTO.getNum()));
        Long userId = BaseContext.getCurrentId();
//        封装Order对象，初识status为未支付
        Order order = new Order();
        order.setStatus(1);
        order.setPaymentType(orderDTO.getPaymentType());
        order.setUserId(userId);
        order.setTotalFee(multiply);
        int insert = orderMapper.insert(order);
        //获取订单id
        Long orderId = order.getId();
        //将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        OrderDetail orderDetail1 = new OrderDetail();
        orderDetail1.setOrderId(orderId);
        orderDetail1.setPrice(multiply);
        orderDetail1.setItemId(item.getId());
        orderDetail1.setNum(orderDTO.getNum());
        orderDetail1.setTitle(item.getName());
        orderDetail1.setImage(item.getImage());
        //获取订单明细id
        int insert1 = orderDetailMapper.insert(orderDetail1);
        Address address = addressFeignClient.findAddressById(Long.valueOf(orderDTO.getAddressId()));
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setOrderId(orderId);
        BeanUtils.copyProperties(address,orderLogistics);


        //调用item-service的减库存接口
        Integer inventory = itemFeignClient.Inventory(item.getId(), Long.valueOf(orderDTO.getNum()));
        return orderId;
    }
}
